package com.jltx.xq.coroutinesandrxpro.coroutines

import android.util.Log
import com.jltx.xq.coroutinesandrxpro.rxjava.RxJava2Learn1
import kotlinx.coroutines.*
import kotlinx.coroutines.selects.select

/**
 * @author aidenquan
 *         Created by junlintianxia on 2021/08/10.
 */
object CoroutinesLearn4 {

    fun selectChannel() {
        GlobalScope.launch(Dispatchers.Main) {

            val local = async(Dispatchers.IO) {
                null
            }

            val remote = async(Dispatchers.IO) {
                delay(2000L)
                "from net data"
            }

            try {
                val userRes = select<Response<String?>> {
                    local.onAwait {
                        Response(it, true)
                    }
                    remote.onAwait {
                        Response(it, false)
                    }
                }

                userRes.value?.let {
                    Log.d(
                        RxJava2Learn1.TAG,
                        "selectChannel userRes.value: $it"
                    )
                } ?: Log.d(
                    RxJava2Learn1.TAG,
                    "selectChannel userRes.value is null"
                )

                //如果选取的本地缓存为空，这时候需要去获取网络结果来显示最新结果
                userRes.isFromCache.takeIf {
                    it
                }?.let {
                    val userFromNet = remote.await()
                    //cacheData 网络获取成功之后缓存到本地

                    Log.d(
                        RxJava2Learn1.TAG,
                        "selectChannel userFromNet.value: $userFromNet"
                    )
                }
            } catch (e: Exception) {
                Log.e(
                    RxJava2Learn1.TAG,
                    "selectChannel e: $e"
                )
            }

        }
    }


    data class Response<T>(val value: T, val isFromCache: Boolean)

}